localStorage.removeItem('ms-t')

//微服务加载完成标记
var msFlag = false
//思极地图加载完成标记
var sgMapFlag = false
//实例页面的回调方法
var pageCallBack = null
// import * as servers from '../libs/httpService.js'
// import servers from '../libs/httpService.js'
//思极地图相关配置
var sgMapSdkUrl = 'https://map.sgcc.com.cn/maps?v=3.0.0'
var sgMapKey = 'fefe3a1d8cf4399cb4cad19d789d156d'
var sgMapSn = '9bf4a465dc0f37129f00cd59cd681ce8'

//微服务相关配置
var msKey = '39602809e8d530dba87b9dab21f08319'
var msSecretKey = 'e0f916e806ff3f97b7d1eca59f1962fa'
// var msServiceUrl = 'sec'
var msServiceUrl = 'http://172.20.50.48:21100'
//电网SDK引用地址
var egisV2Url = '../libs/egis-V2.min.js'
var token = ''
//两个直接访问的出图服务接口(开发环境用)
//切片服务地址
var tileUrl = msServiceUrl + '/mapservice/mapexport/vectile/{z}/{x}/{y}.sg' //微服务地址
// //栅格出图服务地址
var rasterMapServiceUrl = 'http://27.8.2.63:21030/MapServer/json'
var featureslist = []
// var appkey='39602809e8d530dba87b9dab21f08319'
//---------------------------------------微服务鉴权Start---------------------------------------
/**
 * 微服务登录
 */
var map = null
function msLogin() {
  //   TransformationApi.then(params).then((res) => {})
  post(msServiceUrl + '/authorityservice/login/integrate', {
    appkey: msKey,
  })
    .then((res) => {
      if (res.data.success) {
        // console.log("登录成功！");
        // alert('登录成功')
        //step-3:配置sdk对接微服务的参数
        //设置微服务出图参数是否全报文加密(设置true和false都可以，默认是false)
        egisV2.MicroService.serviceInfo.encMode = false //这个是给sdk请求vecformat接口用的参数，vecformat为共享服务，现场无需使用全报文加密
        //设置微服务的token
        egisV2.MicroService.serviceInfo.token = res.data.resultValue.token
        token = res.data.resultValue.token
        // //设置微服务的secretKeyinitMap
        egisV2.MicroService.serviceInfo.secretKey = msSecretKey

        msFlag = true
        initMap()
      } else {
        console.log(res.data.message)
      }
    })
    .catch((e) => {
      console.log('微服务异常', e)
    })
}

//---------------------------------------微服务鉴权End---------------------------------------

//---------------------------------------地图初始化Start---------------------------------------
//地图实例

//当前案例实际使用的出图服务地址
var mapServiceUrl = ''

var mapOptions = {
  style: 'aegis://styles/aegis/StreetsDark',

  // zoom: 5.6,
  // center: {lng: 109.4471291388071, lat: 35.07028691090167},
  zoom: 15, //23,
  center: {
    lng: 118.15988584657646,
    lat: 24.47478491751866,
  },

  maxZoom: 23.5,
}

//纯黑背景，做站内图时用的上
var blackBgStyle = {
  glyphs: 'aegis://fonts/aegis/{fontstack}/{range}.pbf',
  name: '浅色地图',
  sources: {
    epgis: {
      type: 'vector',
      url: 'aegis://aegis.Streets.20200601',
    },
  },
  layers: [
    {
      id: 'background',
      layout: {
        visibility: 'visible',
      },
      paint: {
        'background-color': '#000000',
      },
      type: 'background',
    },
  ],
  sprite: 'aegis://sprites/aegis/Streets',
  version: 8,
}
//显示切片边界
var showTileBoundaries = false
//地图插件列表
var mapPluginList = ['SGMap.EleSymbolLayer']

// ,"SGMap.CustomVectorTileLayer"

/**
 * 加载地理图（包含SGMap.EleSymbolLayer插件）
 * @param callback
 */
function loadGeoMap(callback) {
  dynamicLoadJs(egisV2Url, () => {
    dynamicLoadJs(sgMapSdkUrl, () => {
      pageCallBack = callback
      msFlag = true
      SGMap.tokenTask.login(sgMapKey, sgMapSn).then(function() {
        SGMap.plugin(mapPluginList).then(function(res) {
          sgMapFlag = true
          initMap()
        })
      })
    })
  })
}

/**
 * 加载地理图（包含微服务登录）
 * @param callback
 */
function loadGeoMap_ms(callback) {
  dynamicLoadJs(egisV2Url, () => {
    dynamicLoadJs(sgMapSdkUrl, () => {
      pageCallBack = callback
      SGMap.tokenTask.login(sgMapKey, sgMapSn).then(function() {
        SGMap.plugin(mapPluginList).then(function(res) {
          sgMapFlag = true
          msLogin()
          //   initMap()
        })
      })
      //   msLogin()
    })
  })
}

/**
 * 初始化思极地图
 * @param containerId 地图dom容器的id
 * @returns {Map<any, any>|t|*}
 */
function initMap(containerId) {
  if (!msFlag || !sgMapFlag) {
    return
  }
  map = null
  // egisV2.createMap
  let baseMap = egisV2.createMap({
    container: containerId || 'map',
    style: 'aegis://styles/aegis/Streets',
    doubleClickZoom: true,
    zoom: 15, //23,
    preserveDrawingBuffer: true,
    maxZoom: 23.5,

    center: [112.55241979658, 37.86774288178],
    localIdeographFontFamily: 'Microsoft YoHei',
    ...mapOptions,
  })

  baseMap.showTileBoundaries = showTileBoundaries
  baseMap.egis.selectionSet.setSpeed(5)
  baseMap.on('load', (e) => {
    if (!baseMap.style.stylesheet.glyphs) {
      baseMap.style.stylesheet.glyphs =
        'aegis://fonts/aegis/{fontstack}/{range}.pbf'
      baseMap.style.glyphManager.setURL(
        'aegis://fonts/aegis/{fontstack}/{range}.pbf'
      )
    }

    new SGMap.EleSymbolLayer({ mobile: true, type: 'all' }) //加载电网图数据

    //比例尺        // baseMap.addControl(new SGMap.ScaleControl({
    //     maxWidth: 80,
    //     unit: 'metric'
    // }), 'bottom-left');

    if (pageCallBack) {
      pageCallBack()
    }

    setInfoBarData('ib_mapZoom', baseMap.getZoom())
  })
  //这里是地图点击的测试代码
  baseMap.on('click', function(e) {
    popupDOM = new SGMap.Popup({
      // 是否显示关闭按钮
      // closeButton: false,
      closeOnClick: false,
      offset: {
        bottom: [0, -40],
      },
    })
    selectTool.enable()
    var features = baseMap.queryRenderedFeatures(e.point)

    featureslist.push(features)
    console.log(egisV2.util.DataUtil.degreeToMercator(e.lngLat))
  })
  //
  baseMap.on('zoomend', function(e) {
    console.log('比例尺:  1/', map.getScale())
    if (document.getElementById('ib_mapZoom')) {
      document.getElementById('ib_mapZoom').innerHTML = Number(
        baseMap.getZoom()
      ).toFixed(1)
    }
    console.log('层级:', baseMap.getZoom())
  })

  if (!map) {
    map = baseMap
  }
  return baseMap
}

//---------------------------------------地图初始化End---------------------------------------

//---------------------------------------网格初始化Start---------------------------------------
/**
 * 初始化网格图层
 */

//网格可选参数
var gridCellOptions = {}
//专题图网格图层
var cellLayer = null

function initCellLayer() {
  cellLayer = new egisV2.layer.GridCellLayer({
    map: map,
    bounds: [
      [118.18995135082379, 24.47834215450987],
      [118.19061021844635, 24.478524030580136],
    ],
    lineColor: '#fff',
    lineWidth: 1,
    lineOpacity: 0.3,
    backgroundColor: '#000000',
    backgroundOpacity: 1,
    cellSize: 1, //单元格尺寸1代表实际跨度为0.000009度
    ...gridCellOptions,
  })

  cellLayer.render()
}

//---------------------------------------网格初始化End---------------------------------------

//---------------------------------------选择工具初始化Start---------------------------------------
/**
 * 初始化选择工具
 */

//选择工具
var selectTool = null
//选择工具参数loadGeoMap(
var selectToolOptions = {}
//是否追加选择
var isAddOn = false

function initSelectTool() {
  selectTool = new egisV2.tool.SelectTool(map, {
    type: 'rectangle', //支持point，circle，rectangle，polygon
    borderWidth: 2, //绘制过程中的边框宽度
    borderColor: '#009ecc', //绘制过程中的边框颜色
    fillColor: '#009ecc', //绘制过程中的填充色
    fillOpacity: 0.5, //绘制过程中的填充透明度
    // layers: ['301000']//打开此选项，可以过滤被选中的目标图层selectToolOptions
    selectedColor: '#ff00ff',

    isAddOn: isAddOn,
    // cursorStyle: 'crosshair',
    ...selectToolOptions,
  })

  selectTool.on(egisV2.event.SelectEvent.DEVS_SELECTED, (e) => {
    console.log(snapToolOptions, '哈哈哈')
    console.log(selectToolOptions)
    // console.log('当前选中的设备集合:' + selectTool._type)
    console.log(e)
  })
}

//---------------------------------------选择工具初始化End---------------------------------------

//---------------------------------------捕捉工具初始化Start---------------------------------------
/**
 * 初始化捕捉工具
 */

//捕捉工具参数
var snapToolOptions = {}
//捕捉工具
var snapTool = null
//捕捉到的设备数据
var snapedData = null

function initSnapTool() {
  snapTool = new egisV2.tool.SnapTool(map, {
    // layers: ['3201000'],
    // types: ['terminal','line'],
    priority: ['terminal', 'line'],
    // cursorStyle: 'crosshair',
    tolerance: 20,
    layers: null,
    // layers: [115000 ,110000 ,190000 ,201000 ,190000 ,110000 ,116000 ,140000 ,111000 ,3216000,102000 ,170000 ,112000 ,4106000,119000 ,113000 ,110000 ,160000 ,130000 ,118000 ,120000 ,180000 ,115000 ,114000 ,115000 ,190000 ,121000 ,8190000,102000 ,180000 ,202000],
    types: ['cellPoint', 'cellLine', 'point', 'line', 'terminal'],
    fillTypes: ['10300001'],
    // fillTypes:[],
    cursorStyle: 'crosshair',
    snapColors: {
      point: '#00ffeb',
      line: '#00ffeb',
      terminal: '#ff0000',
      cellLine: '#00ffeb',
      cellPoint: '#00ffeb',
    },
    ...snapToolOptions,
  })

  snapTool.on(egisV2.event.SnapEvent.DEV_SNAPPED, (e) => {
    if (e && e.geomType != 'cellLine' && e.geomType != 'cellPoint') {
      snapedData = e
      console.log(e.geomType)
      console.log(e)
    } else {
      snapedData = null
    }
  })

  map.on('click', (e) => {
    // 初始化Popup

    if (snapedData) {
      console.log('捕捉到的数据:-------------', new Date().getTime())
      console.log('SnapData:', snapedData)
      console.log('-------------------------')
    }
  })
  map.on('zoomend', (e) => {
    console.log('层级:' + map.getZoom())
    console.log('比例尺:1/' + map.getScale())
  })
}

//---------------------------------------捕捉工具初始化End---------------------------------------

//---------------------------------------电网矢量栅格图层初始化Start---------------------------------------
/**
 * 初始化电网矢量切片图层
 */

var gridTileLayer = null
//切片图层参数
var tileOptions = {}

function initGridTileLayer() {
  //按需隐藏建筑图层
  map.setLayoutProperty('Building', 'visibility', 'none')
  //创建切片图层
  gridTileLayer = new egisV2.layer.GridTileLayer({
    map: map,
    // layers:['300000','198812'],
    url: tileUrl,
    maxLevel: 18,
    tileSize: 512,
    cacheId: '', //缓存ID，默认图层自动生成
    ...tileOptions,
  })
  let startTime = new Date().getTime()
  gridTileLayer.on('startLoadingData', (e) => {
    startTime = new Date().getTime()
    setInfoBarData('ib_gridTime', '加载中')
  })
  gridTileLayer.on('endLoadingData', (e) => {
    let during = new Date().getTime() - startTime
    setInfoBarData('ib_gridTime', Number(during / 1000).toFixed(2) + '秒')
  })

  // gridTileLayer.on(egisV2.event.GridVectorLayerEvent.BEFORE_RENDER, e => {
  //     //请勿再次事件的回调方法内调用gridTileLayer的render方法，这么做会导致循环调用
  //     console.log('切片即将渲染' + new Date().getTime())
  // })
  gridTileLayer.on(
    egisV2.event.GridVectorLayerEvent.BEFORE_RENDER,
    async (e) => {
      // let sss = await new Promise((resolve, reject) => {
      //     setTimeout(() => {
      //         resolve('999' + Math.random())
      //     }, 3000)
      // })
      // e.test = 'cxz'
    }
  )

  gridTileLayer.on(egisV2.event.GridVectorLayerEvent.AFTER_RENDER, (e) => {
    //请勿再次事件的回调方法内调用gridTileLayer的render方法，这么做会导致循环调用
    console.log('切片渲染完成' + new Date().getTime())
  })

  gridTileLayer.render()
}
//---------------------------------------电网矢量栅格图层初始化End---------------------------------------

//---------------------------------------电网矢量栅格图层初始化Start---------------------------------------
/**
 * 初始化电网图层
 */

//电网图需要加载的图层
var layers = []
//电网图的过滤条件
var displayFilter = []
//矢量栅格图层参数
var gridLayerOptions = {}
//矢量电网图层实例
var gridLayer = null
//调试用(无需调整)
var workerUrl = ''

// workerUrl = './libs/grid-data-parser-gl.js'

function initGridLayer() {
  //这个data参数中的各个属性与电网SDK的FeaturesLayer中的相关参数是一致的（即栅格服务的出图参数）
  // gridLayer = new egisV2.layer.GridVectorExtLayer({
  gridLayer = new egisV2.layer.GridVectorLayer({
    map: map, //思极地图的map对象实例
    url: mapServiceUrl, //栅格出图服务地址
    workerUrl: workerUrl,
    method:
      mapServiceUrl == msServiceUrl + '/mapservice/mapexport/vecformat'
        ? 'POST'
        : 'GET', //直连使用get请求，微服务使用post请求
    data: {
      layers: layers.join(','), //要显示的图层
      displayfilter: displayFilter, //这个参数可以使用数组格式，如[{'300000':'dydj = 3'}],也可以将数组格式的数据通过JSON.stringify转成字符串，sdk这里有做兼容处理。
      mapid: 110,
      maptype: 1001,
      hidelayers: '1102000',
      // FILTERFLYLINE: 1,//是否过滤飞线
      // FLYLINELENGTH: 2500 * 10,//判定为飞线的最小距离

      // disschema: 1,
      ...gridLayerOptions,
    },
    // compareUrl: 'http://27.196.200.208:9668/MapServer/json/'
  })

  let startTime = new Date().getTime()
  gridLayer.on('startLoadingData', (e) => {
    startTime = new Date().getTime()
    setInfoBarData('ib_gridTime', '加载中')
  })
  gridLayer.on('endLoadingData', (e) => {
    let during = new Date().getTime() - startTime
    setInfoBarData('ib_gridTime', Number(during / 1000).toFixed(2) + '秒')
  })
  let lineTypeList = [
    1,
    410,
    420,
    421,
    10026,
    30058,
    30059,
    30061,
    42401,
    42701,
    42801,
    100000,
    2010010,
    2010011,
    2010012,
    2010020,
    3010010,
    4250010,
    4260010,
    6040010,
    7010010,
    7010011,
    7010012,
    7020010,
    7030010,
    7040010,
    9050012,
    9050014,
    70200201,
    70200202,
    70200203,
    70200204,
  ]
  let len = lineTypeList.length
  //渲染前
  gridLayer.on(egisV2.event.GridVectorLayerEvent.BEFORE_RENDER, async (e) => {
    // for(let layerid in e.data){
    //     if(e.data[layerid].type == 'eline'){
    //        for(let index = 0;index < e.data[layerid].features.length;index++){
    //            e.data[layerid].features[index].properties.id = lineTypeList[Math.floor(Math.random() * len)]
    //        }
    //     }
    // }
    // console.log(123)
    // let result = await new Promise((resolve,reject) => {
    //     setTimeout(() => {
    //         console.log(123)
    //         resolve('Promise已执行')
    //     },5000)
    // })
    // console.log('222' + result)
    //每次请求到的电网数据可以在这里获取并供业务层使用
    //完成之后调用该方法执行渲染（即用户可以在渲染前随意修改数据）
    //渲染前调可以自行增删改数据
    // e.keys.splice(e.keys.indexOf('301000'),1)
    // e.keys.splice(e.keys.indexOf('301000_extend'),1)
    // delete e.data['301000']
    // delete e.data['301000_extend']
    //请勿再次事件的回调方法内调用gridVectorLayer的render方法，这么做会导致循环调用
    // e.data['300000'] =   {
    //     "features": [{
    //         "type": "Feature",
    //         "geometry": {
    //             "type": "Polygon",
    //             "coordinates": [[[118.05607270652222, 24.476077372390183], [118.05607270652222, 24.475987440353816], [118.05587508293961, 24.475987440353816], [118.05587508293961, 24.476077372390183], [118.05607270652222, 24.476077372390183]]]
    //         },
    //         "properties": {
    //             "apptype": "0",
    //             "byteNodetype": 131403,
    //             "color": "#b94842",
    //             "dydj": "22",
    //             "id": 20011,
    //             "layerid": 300000,
    //             "oid": 1500722366,
    //             "opacity": 1,
    //             "outline": 1,
    //             "rotate": "0",
    //             "sbid": "1FD3B9A5-252F-4E31-B066-D955A06914D8",
    //             "sbzlx": "32300000",
    //             "scalable": true,
    //             "size": 0.5,
    //             "stateid": "5011371901",
    //             "zoom": 0,
    //             "hasTerminal": false,
    //             "terminalCount": 0,
    //             "shape": {
    //                 "type": "Polygon",
    //                 "coordinates": [[[118.05607270652222, 24.476077372390183], [118.05607270652222, 24.475987440353816], [118.05587508293961, 24.475987440353816], [118.05587508293961, 24.476077372390183], [118.05607270652222, 24.476077372390183]]]
    //             },
    //             "geotype": 3,
    //             "geometrytype": 3,
    //             "oriSize": 0.5
    //         }
    //     }],
    //     "layout": {},
    //     "paint": {"fill-color": "rgba(0,0,0,0)", "fill-outline-color": ["get", "color"],"fill-color":["get", "color"]},
    //     "type": "fill"
    // }
    // console.log('渲染开始:' + new Date().getTime())
  })

  gridLayer.on(egisV2.event.GridVectorLayerEvent.HANDLE_DEV, (dev) => {
    //请勿再次事件的回调方法内调用gridVectorLayer的render方法，这么做会导致循环调用
    //每个电网设备在叠加本地设备缓存之后，渲染之前会触发该回调，业务层可以在这里对属性进行对应判断，例如检测到了批次号就可以删除本地缓存
    // console.log(dev)
  })

  //渲染后
  gridLayer.on(egisV2.event.GridVectorLayerEvent.AFTER_RENDER, () => {
    // console.log('渲染结束:' + new Date().getTime())
  })
  //渲染出错
  gridLayer.on(egisV2.event.GridVectorLayerEvent.ERROR_RENDER, (err) => {
    // console.log('渲染出错:' + new Date().getTime())
  })

  gridLayer.on(
    egisV2.event.GridVectorLayerEvent.BEFORE_REQUEST,
    async (data) => {
      // let sss = await new Promise((resolve, reject) => {
      //     setTimeout(() => {
      //         resolve('999' + Math.random())
      //     }, 3000)
      // })
      // data.postdata.kaito = sss
    }
  )
  gridLayer.render()
}
//---------------------------------------电网矢量栅格图层初始化End---------------------------------------

//---------------------------------------电网矢量切片图层初始化Start---------------------------------------
/**
 * 创建矢量切片图层
 */

var gteLayer = null
var gridTileExtLayerOptions = {}

function initGridTileExtLayer() {
  //雪碧图及其描述文件的资源路径
  let resPath = location.pathname.split('/')
  resPath.pop()
  resPath = resPath.join('/')
  let spritePath = '/static/example/example/assets/tileExt/sprite'

  //创建切片图层
  gteLayer = new egisV2.layer.GridTileExtLayer({
    map: map,
    urls: [msServiceUrl + '/mapservice/mapexport/vectile/{z}/{x}/{y}.sg'],
    layerConf: layerJson,
    spriteUrl: spritePath,
    sourceOptions: {
      maxzoom: 18,
    },
    ...gridTileExtLayerOptions,
  })

  gteLayer.setRequestParam({
    request: 'getmap',
    X: '{x}',
    Y: '{y}',
    Z: '{z}',
  })

  gteLayer.on(egisV2.event.GridVectorLayerEvent.BEFORE_RENDER, (e) => {
    console.log('开始加载数据')
  })

  let startTime = new Date().getTime()
  gteLayer.on('startLoadingData', (e) => {
    startTime = new Date().getTime()
    setInfoBarData('ib_gridTime', '加载中')
  })
  gteLayer.on('endLoadingData', (e) => {
    let during = new Date().getTime() - startTime
    setInfoBarData('ib_gridTime', Number(during / 1000).toFixed(2) + '秒')
  })
  gteLayer.setLayersFilter({
    '100000': ['any', ['in', 'dydj', 22]],
    '300000': ['any', ['in', 'dydj', 22]],
  })

  gteLayer.render()
  //设置选择集模式为mapbox来兼容GridTileExtLayer
  map.egis.selectionSet.setMode('mapbox')
  map.egis.selectionSet.setAutoFlicker(true)
  map.egis.selectionSet.setFlicker(true)

  map.egis.selectionSet.setSpeed(5)
}
//---------------------------------------电网矢量切片图层初始化End---------------------------------------

//---------------------------------------公共方法Start---------------------------------------
/**
 * 动态加载JS
 * @param {String} url 脚本地址
 * @param {Function} callback  回调函数
 */
var dynamicLoadJs = function(url, callback) {
  var head = document.getElementsByTagName('head')[0]
  var script = document.createElement('script')
  script.type = 'text/javascript'
  script.src = url
  if (typeof callback == 'function') {
    script.onload = script.onreadystatechange = function() {
      if (
        !this.readyState ||
        this.readyState === 'loaded' ||
        this.readyState === 'complete'
      ) {
        callback()
        script.onload = script.onreadystatechange = null
      }
    }
    script.onerror = function(err) {
      alert('请在弹出页面确认安全问题后回来刷新本页面')
      window.open(url, '_blank')
    }
  }
  head.appendChild(script)
}

/**
 * 初始化状态栏
 */
function initInfoBar() {
  let infoBar = document.createElement('div')
  infoBar.classList.add('infoBar')
  document.body.appendChild(infoBar)
  document.querySelector(
    '.infoBar'
  ).innerHTML = `<div>层级:<label id="ib_mapZoom">0</label></div><div>电网加载耗时:<label id="ib_gridTime">0</label></div>`
}

/**
 * 给状态栏的dom节点写数据
 * @param domId
 * @param text
 */
function setInfoBarData(domId, text) {
  if (document.getElementById(domId)) {
    document.getElementById(domId).innerHTML = text
  }
}
//---------------------------------------公共方法End---------------------------------------

window.locateByLocation = function(center, zoom) {
  let dCenter = null
  let tmpPoint = null
  if (center instanceof Array) {
    tmpPoint = { x: center[0], y: center[1] }
  } else if (center.lng && center.lat) {
    tmpPoint = { x: center.lng, y: center.lat }
  }

  if (tmpPoint.x > 180 || tmpPoint.x < -180) {
    dCenter = egisV2.util.DataUtil.mercatorToDegree(tmpPoint)
  } else {
    dCenter = { lng: tmpPoint.x, lat: tmpPoint.y }
  }

  map.jumpTo({
    center: dCenter,
    zoom: zoom,
  })
}
